package com.aramis.mydytt.ui.detail

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aramis.mydytt.R
import com.aramis.mydytt.db.FavoriteManager
import com.aramis.mydytt.db.FavoriteMovieBean
import com.aramis.mydytt.ext.logE
import com.aramis.mydytt.ui.bean.MovieCommentBean
import com.aramis.mydytt.ui.bean.MovieDetailBean
import com.aramis.mydytt.ui.bean.MovieDetailDownListBean
import com.aramis.mydytt.ui.bean.MovieItemBean
import com.aramis.mydytt.ui.dialog.DetailDescriptionDialog
import com.aramis.mydytt.ui.dialog.DetailDownloadDialog
import com.aramis.mydytt.widget.RatingBar
import com.facebook.drawee.view.SimpleDraweeView
import java.lang.Exception
import java.lang.StringBuilder

/**
 * Description: MovieDetailActivity
 * 电影详情
 * @author lizhidan
 * Created: 2021/4/7
 */
class MovieDetailActivity : AppCompatActivity() {
    companion object {
        private const val KEY_DATA = "data"
        fun start(context: Context, bean: MovieItemBean) {
            val intent = Intent(context, MovieDetailActivity::class.java)
            intent.putExtra(KEY_DATA, bean)
            context.startActivity(intent)
        }
    }

    private lateinit var viewModel: MovieDetailViewModel
    private lateinit var bean: MovieItemBean
    private lateinit var leftBottomLayout: ViewGroup
    private lateinit var rightBottomLayout: ViewGroup
    private lateinit var titleView: TextView
    private lateinit var titleSecView: TextView
    private lateinit var commentListView: RecyclerView
    private lateinit var descriptionLayout: ViewGroup
    private lateinit var descriptionTextView: TextView
    private lateinit var descriptionMoreTextView: TextView
    private lateinit var detailDescriptionDialog: DetailDescriptionDialog//简介dialog
    private lateinit var downloadDialog: DetailDownloadDialog//下载dialog
    private val commentAdapter = MovieCommentAdapter()
    private lateinit var commentNumView: TextView
    private lateinit var favoriteImageView: AppCompatImageView
    private var favoriteBean: FavoriteMovieBean? = null//"喜欢"标记
    private lateinit var downloadedImageView: AppCompatImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_movie_detail)
        viewModel = ViewModelProvider(this).get(MovieDetailViewModel::class.java)
        bean = intent.getSerializableExtra(KEY_DATA) as MovieItemBean
        logE("电影详情：id:${bean.id},name:${bean.title}")
        initView()
        setListener()
        initData()
    }

    private fun setListener() {
        //喜欢
        leftBottomLayout.setOnClickListener {
            viewModel.addOrRemoveFavorite(favoriteBean, bean)
        }
        //下载按钮
        rightBottomLayout.setOnClickListener {
            downloadDialog.show()
        }
        //简介详情
        descriptionMoreTextView.setOnClickListener {
            detailDescriptionDialog.show()
        }
        //下载dialog回调
        downloadDialog.setOnDownloadListItemClickListener {
            val result = downloadFileByXunlei(it)
            if (result != null) {
                Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
            } else {
                viewModel.markDownloaded(bean)
            }
        }
    }

    private fun initView() {
        detailDescriptionDialog = DetailDescriptionDialog(this)
        downloadDialog = DetailDownloadDialog(this)
        leftBottomLayout = findViewById(R.id.layout_detail_bottom_left)
        rightBottomLayout = findViewById(R.id.layout_detail_bottom_right)
        titleView = findViewById(R.id.text_movie_name)
        titleSecView = findViewById(R.id.text_movie_title_sec)
        descriptionLayout = findViewById(R.id.layout_movie_info)
        descriptionTextView = findViewById(R.id.text_detail_info_content)
        descriptionMoreTextView = findViewById(R.id.text_detail_info_go)
        commentNumView = findViewById(R.id.text_detail_comment_num)
        favoriteImageView = findViewById(R.id.image_detail_favorite)
        downloadedImageView = findViewById(R.id.image_detail_downloaded)
        commentListView = findViewById(R.id.list_detail_comment)
        commentListView.adapter = commentAdapter
        commentListView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        findViewById<View>(R.id.image_detail_back).setOnClickListener {
            onBackPressed()
        }
        findViewById<RatingBar>(R.id.rating_bar_detail).setScore(bean.score ?: "0.0")
        initViewByItemBean()
    }

    private fun initViewByItemBean() {
        detailDescriptionDialog.setMovieName(bean.title)
        downloadDialog.setMovieName(bean.title)
        findViewById<SimpleDraweeView>(R.id.image_detail_cover).setImageURI(bean.path)
        setMovieTitle(bean.title)
    }

    private fun initData() {
        viewModel.detailLiveData.observe(this, {
            if (it != null) {
                showContentView(it)
                detailDescriptionDialog.setData(it)
                downloadDialog.setData(it)
            }
        })
        viewModel.commentLiveData.observe(this, {
            showCommentList(it)
        })
        viewModel.dyttMovieDetailLiveData.observe(this, {
            downloadDialog.setDyttDownloadData(it)
        })
        viewModel.getMovieDetail(bean)
        viewModel.favoriteCheckLiveData.observe(this, {
            favoriteBean = it
            updateFavoriteView(it != null)
        })
        viewModel.downloadedLiveData.observe(this, {
            updateDownloadedView(it != null)
        })
        viewModel.checkFavorite(bean.id)
        viewModel.checkDownLoaded(bean.id)
    }

    private fun updateFavoriteView(favorite: Boolean) {
        if (favorite) {
            favoriteImageView.setImageResource(R.drawable.ic_favorites)
            favoriteImageView.setColorFilter(Color.RED)
        } else {
            favoriteImageView.setImageResource(R.drawable.ic_favorites_un)
            favoriteImageView.setColorFilter(Color.WHITE)
        }
    }

    private fun updateDownloadedView(downloaded: Boolean) {
        if (downloaded) {
            downloadedImageView.setImageResource(R.drawable.ic_download)
            downloadedImageView.setColorFilter(Color.BLUE)
        } else {
            downloadedImageView.setImageResource(R.drawable.ic_download)
            downloadedImageView.setColorFilter(Color.YELLOW)
        }
    }

    private fun showContentView(bean: MovieDetailBean) {
        setMovieTitleSec(bean.year?.title, bean.duration, bean.area?.title, bean.update_cycle)
        if (bean.description != null && bean.description.isNotBlank()) {
            descriptionLayout.visibility = View.VISIBLE
            descriptionTextView.text = bean.description
        } else {
            descriptionLayout.visibility = View.GONE
        }
    }

    private fun setMovieTitle(title: String?) {
        titleView.text = title
    }

    private fun setMovieTitleSec(year: String?, duration: String?, area: String?, updateCycle: String?) {
        val stringBuilder = StringBuilder()
        appendValidStr(stringBuilder, year)
        appendValidStr(stringBuilder, duration)
        appendValidStr(stringBuilder, area)
        appendValidStr(stringBuilder, updateCycle)
        titleSecView.text = stringBuilder.toString()
    }

    private fun appendValidStr(s: StringBuilder, str: String?) {
        if (str != null && str.isNotBlank()) {
            if (s.isNotEmpty()) {
                s.append("·")
            }
            s.append(str)
        }
    }

    private fun showCommentList(commentList: List<MovieCommentBean>?) {
        if (commentList != null && commentList.isNotEmpty()) {
            commentNumView.text = getString(R.string.str_detail_comment_num, commentList.size)
            commentAdapter.setData(commentList)
        } else {
            commentNumView.visibility = View.GONE
            commentListView.visibility = View.GONE
        }
    }

    private fun downloadFileByXunlei(movieDetailDownListBean: MovieDetailDownListBean): String? {
        var result: String? = null
        try {
            val url = "AA" + movieDetailDownListBean.url + "ZZ"
            val base64Token = Base64.encodeToString(url.toByteArray(), Base64.DEFAULT).replace("\n", "")
            logE("原地址：${movieDetailDownListBean.url}")
            logE("迅雷链接：$base64Token")
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("thunder://$base64Token"))
            intent.addCategory("android.intent.category.DEFAULT")
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            result = "未找到迅雷app，请下载后重试"
        }
        return result
    }
}